<template>
  <div ref="componentWrap" class="component-wrap">
    <div ref="subtitlesWrap" class="subtitles-wrap" :style="wrapStyle"></div>
    <ShowBorder v-if="borderShow" :border-attrs="borderAttrs" />
  </div>
</template>

<script>
import { mapState } from 'vuex'
import ShowBorder from '@/components/Editor/ShowBorder.vue'
import { pick } from 'lodash'
import { borderAttr } from '@/custom-component/component-list'
import { TextCanvas } from '@/utils/animation'

export default {
  name: 'Subtitles',
  components: { ShowBorder },
  props: {
    element: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {}
  },
  computed: {
    ...mapState(['curComponent']),
    borderAttrs() {
      const attrs = Object.keys(borderAttr)
      return pick(this.element, [...attrs, 'width', 'height', 'id'])
    },
    borderShow() {
      return Number(this.element?.borderSW) === 1
    },
    wrapStyle() {
      const { width, height } = this.element
      return {
        width: `${width}px`,
        height: `${height}px`,
      }
    },
  },
  watch: {
    element: {
      deep: true,
      handler(newVal) {
        const watchVal = JSON.stringify(
          pick(newVal, [
            'textDecoration',
            'textAlign',
            'textGroup',
            'siderType',
            'scrollSpeed',
            'rotate',
            'pauseTime',
            'lineHeight',
            'fontWeight',
            'fontStyle',
            'fontSize',
            'fontFamily',
            'fontColor',
            'textShow',
            'srcGroup',
            'width',
            'height',
            'borderColoreffect',
            'background',
          ]),
        )

        if (watchVal !== this.oldVal) {
          this.$nextTick(() => {
            this.subtitle.restCanvas(this.element)
          })
        }

        this.oldVal = watchVal
      },
    },
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.subtitle.dispose()
  },
  methods: {
    init() {
      this.subtitle = new TextCanvas(this.$refs.subtitlesWrap, {
        data: this.element,
      })

      this.subtitle.init()
    },
  },
}
</script>
<style lang="scss" scoped></style>
